package comment

import (
	"context"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/rpc/forumclient"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreatePostCommentLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 发布评论
func NewCreatePostCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePostCommentLogic {
	return &CreatePostCommentLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreatePostCommentLogic) CreatePostComment(req *types.PostCommentInfo, ip string) (resp *types.CreatePostCommentResp, err error) {
	if req.CommentContent == nil {
		return nil, resultx.StatusError(resultx.FORUM_COMMENT_CONTENT_REQUIRED, "")
	} else if len(strings.TrimSpace(*req.CommentContent)) == 0 {
		return nil, resultx.StatusError(resultx.FORUM_COMMENT_CONTENT_REQUIRED, "")
	}
	if req.PostId == nil {
		return nil, resultx.StatusError(resultx.FORUM_POST_ID_REQUIRED, "")
	} else if *req.PostId == 0 {
		return nil, resultx.StatusError(resultx.FORUM_POST_ID_REQUIRED, "")
	}
	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}
	userInfo, err := l.svcCtx.UserRpc.GetUserAuthByUserId(l.ctx, &userclient.GetUserAuthByUserIdReq{
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
		UserId:     pointy.GetPointer(userId),
		WithRank:   pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		logx.Infow("CreatePostComment UserRpc.GetUserAuthByUserId err", logx.Field("detail", err.Error()))
		return nil, resultx.NewErrCode(resultx.USER_GET_INFO_FAILED)
	}
	if userInfo.Openid == nil {
		return nil, resultx.NewErrCode(resultx.USER_GET_INFO_FAILED)
	}
	var data = &forumclient.PostCommentInfo{
		PostId:         req.PostId,
		UserId:         pointy.GetPointer(userId),
		NickName:       userInfo.Nickname,
		UserAvatar:     userInfo.Avatar,
		CommentContent: req.CommentContent,
	}
	if req.ForumId != nil && *req.ForumId > 0 {
		data.ForumId = req.ForumId
	}
	if req.ParentId != nil && *req.ParentId > 0 {
		data.ParentId = req.ParentId
	}
	if len(strings.TrimSpace(ip)) > 0 {
		data.Ip = pointy.GetPointer(ip)
	}
	if req.AnonymousUser != nil && *req.AnonymousUser > 0 {
		data.AnonymousUser = req.AnonymousUser
	}
	if req.CommentType != nil && *req.CommentType > 0 {
		data.CommentType = req.CommentType
	}
	if req.Status != nil && *req.Status > 0 {
		data.Status = req.Status
	} else {
		data.Status = pointy.GetPointer(uint32(globalkey.StatusPending))
	}
	res, err := l.svcCtx.ForumRpc.CreatePostComment(l.ctx, data)
	if err != nil {
		return nil, err
	}

	return &types.CreatePostCommentResp{
		Id: pointy.GetPointer(res.Id),
	}, nil
}
